﻿using rmTest.Common.ExtensionUtil;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;



namespace DemormTest.Common.ExtensionUtil
{
    /// <summary>
    /// 对象扩展方法
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        /// 通过判定对象类型，把值转换为指定类型，并返回
        /// </summary>
        /// <param name="value">要转换的值</param>
        /// <param name="ConvertToTheType">要转换的类型</param>
        /// <returns>结果值</returns>
        public static object ConvertToTheType(this object value, Type theType)
        {
            if (value == null || value is DBNull)
            {
                return null;
            }

            //如果是Nullable类型
            if (theType.IsNullableType())
            {
                theType = theType.GetBaseType();
            }

            //枚举类型
            if (theType.IsEnum)
            {
                return Enum.Parse(theType, value.ToString());
            }

            if (theType == typeof(Guid))
            {
                Guid newGuid;
                Guid.TryParse(value.ToString(), out newGuid);
                return newGuid;
            }

            if (value?.GetType() == typeof(Guid))
            {
                return value.ToString();
            }

            return Convert.ChangeType(value, theType);
        }

        /// <summary>
        /// 通过判定对象类型，把值转换为指定类型，并返回
        /// </summary>
        /// <typeparam name="T">动态类型</typeparam>
        /// <param name="value">要转换对象</param>
        /// <returns>转化后的指定类型的对象值</returns>

        public static T ConvertToTheType<T>(this object value)
        {
            return (T)ConvertToTheType(value, typeof(T));
        }

        /// <summary>
        /// 是否为Null
        /// </summary>
        /// <param name="value">判断的值</param>
        /// <returns>true为null,false不为null</returns>
        public static bool IsNull(this object value)
        {
            return value == null ? true : false;
        }
    }
}
